package cn.stylefeng.guns.modular.robot.utils;

import cn.stylefeng.guns.modular.robot.entity.vo.resp.TgFileResp;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.send.SendPhoto;
import org.telegram.telegrambots.meta.api.objects.*;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class RobotUtils {

    private static Logger log = LoggerFactory.getLogger(RobotUtils.class);
    private static final String URL = "https://api.telegram.org/bot";

    public static void sendText(Long chatId, String text, TelegramLongPollingBot bot) {
        sendText(chatId, text, null, bot);
    }

    public static void sendText(Long chatId, String text, Integer replyToMessageId, TelegramLongPollingBot bot) {
        log.info("群消息回复：群名id：" + chatId + "，消息内容:" + text + "，回复消息id'：" + replyToMessageId);
        SendMessage sendMessage = new SendMessage();
        sendMessage.setChatId(chatId);
        sendMessage.setText(text);
        sendMessage.setReplyToMessageId(replyToMessageId);
        sendMessage.enableHtml(true);
        try {
            bot.execute(sendMessage);
        } catch (TelegramApiException e) {
            throw new RuntimeException(e);
        }
    }

    public static void sendTextButton(Long chatId, String text, String buttonName, String url, Integer replyToMessageId, TelegramLongPollingBot bot) {
        log.info("群消息回复：群名id：" + chatId + "，消息内容:" + text + "，回复消息id'：" + replyToMessageId);
        SendMessage sendMessage = new SendMessage();
        sendMessage.setChatId(chatId);
        sendMessage.setText(text);
        sendMessage.setReplyToMessageId(replyToMessageId);
        sendMessage.enableHtml(true);
        List<List<InlineKeyboardButton>> keyboard = new ArrayList<>();
        List<InlineKeyboardButton> inlineKeyboardButtons = new ArrayList<>();
        InlineKeyboardButton inlineKeyboardButton = new InlineKeyboardButton();
        inlineKeyboardButton.setText(buttonName);
        inlineKeyboardButton.setUrl(url);
        inlineKeyboardButtons.add(inlineKeyboardButton);
        keyboard.add(inlineKeyboardButtons);
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        inlineKeyboardMarkup.setKeyboard(keyboard);
        sendMessage.setReplyMarkup(inlineKeyboardMarkup);
        try {
            bot.execute(sendMessage);
        } catch (TelegramApiException e) {
            throw new RuntimeException(e);
        }
    }

    public static Message sendPhoto(Long chatId, Integer replyToMessageId, String caption, InputStream photo, String fileName, TelegramLongPollingBot bot) {
        try {
            log.info("群图片消息回复：群名id：" + chatId + "，消息内容:" + caption);
            InputFile inputFile = new InputFile();
            inputFile.setMedia(photo, fileName);
            SendPhoto sendPhoto = new SendPhoto();
            sendPhoto.setChatId(chatId);
            sendPhoto.setReplyToMessageId(replyToMessageId);
            sendPhoto.setCaption(caption);
            sendPhoto.setPhoto(inputFile);
            return bot.execute(sendPhoto);
        } catch (TelegramApiException e) {
            throw new RuntimeException(e);
        }
    }

    public static Message sendPhoto(Long chatId, String caption, InputStream photo, String fileName, TelegramLongPollingBot bot) {
        return sendPhoto(chatId, null, caption, photo, fileName, bot);
    }

    public static TgFileResp.Result downloadFileAsStream(RestTemplate restTemplate, Update update, TelegramLongPollingBot bot) throws TelegramApiException {
        String botToken = bot.getBotToken();
        List<PhotoSize> photos = update.getMessage().getPhoto();
        PhotoSize photoSize = photos.get(photos.size() - 1);
        ResponseEntity<TgFileResp> tgFileRespResponse = restTemplate.getForEntity(URL + botToken + "/getFile?file_id=" + photoSize.getFileId(), TgFileResp.class);
        HttpStatus statusCode = tgFileRespResponse.getStatusCode();
        if (!HttpStatus.OK.equals(statusCode)) {
            log.error("注意图片转发失败：获取filePath失败!参数：" + URL + botToken + "/getFile?file_id=" + photoSize.getFileId());
            return null;
        }
        TgFileResp.Result result = tgFileRespResponse.getBody().getResult();
        if (Objects.isNull(result)) {
            log.error("注意图片转发失败：获取filePath接口返回空!");
            return null;
        }
        String filePath = result.getFile_path();
        if (StringUtils.isBlank(filePath)) {
            log.error("注意图片转发失败：filePath为空");
            return null;
        }
        InputStream inputStream = bot.downloadFileAsStream(filePath);
        result.setInputStream(inputStream);
        return result;
    }
}
